package com.zjp;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

public class UDataTypeAdapter extends TypeAdapter<UData> {
    @Override
    public void write(JsonWriter out, UData value) throws IOException {
        if (value == null) {
            out.nullValue();
            return;
        }
        out.beginObject();
        out.name("name").value(value.getName() + "--" + value.getAge());
        out.endObject();
    }

    @Override
    public UData read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        in.beginObject();
        System.out.println("in.nextName() = " + in.nextName());
        String[] split = in.nextString().split("--");
        in.endObject();
        return new UData(split[0], Integer.valueOf(split[1]));
    }
}
